package com.hxkj.service.taglib.impl;

import com.alibaba.fastjson.JSONObject;
import com.hxkj.client.service.AnalyzeColumnServiceClient;
import com.hxkj.client.service.ArticleServiceClient;
import com.hxkj.client.service.ColumnServiceClient;
import com.hxkj.domain.enums.ColumnExceptionEnum;
import com.hxkj.domain.po.Article;
import com.hxkj.domain.po.AuthUser;
import com.hxkj.domain.po.Column;
import com.hxkj.domain.po.FreeMarker;
import com.hxkj.service.taglib.AnalyzeColumnService;
import com.hxkj.token.utils.TokenUtils;
import com.hxkj.utils.HanyuPinyinHelper;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.exception.CustomMessageException;
import com.platform.common.domain.result.ParameterDataStruct;
import com.platform.common.domain.result.ResultDataStruct;
import com.platform.common.domain.result.ResultPageStruct;
import com.platform.common.domain.to.PageTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import static com.hxkj.domain.Constant.CmsConstants.COLUMNLIST;

/**
 * @ClassName AnalyzeColumnServiceImpl
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/7/20 17:18
 * @Version 1.0
 */
@Service
@Slf4j
public class AnalyzeColumnServiceImpl implements AnalyzeColumnService {
    @Autowired
    private ColumnServiceClient columnServiceClient;

    @Autowired
    private AnalyzeColumnServiceClient analyzeColumnServiceClient;

    @Autowired
    private ArticleServiceClient articleServiceClient;

    @Autowired
    private TokenUtils tokenUtils;

    /**
     * 生成分类静态文件
     * @param freeMarker
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject analyzeColumn(FreeMarker freeMarker) throws Exception {
        try {
            if (freeMarker.getColumnId() == null) {
                throw new CustomException(ColumnExceptionEnum.COLUMN_NOT_EXIST);
            }
            AuthUser auser = (AuthUser) tokenUtils.getTokenUserInfo();
            freeMarker.setUserToken(String.valueOf(auser.getUserId()));
            Column column = new Column();
            column.setColumnId(freeMarker.getColumnId());
            column.setSiteId(freeMarker.getSiteId());
            // 生成分类静态时根据分类id获取分类数据
            column = columnServiceClient.getColumn(column);
            if (column.getTempId() == null) {
                throw new CustomException(ColumnExceptionEnum.COLUMN_AS_CREATE_TEMPLTE_NOT_EXIST);
            }
            JSONObject jsonObject = getAnalyzePathByColumn(freeMarker, column);
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 文章分类模板可视化
     * @param freeMarker
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject visualizationColumn(FreeMarker freeMarker) throws Exception {
        try {
            Column column = new Column();
            column.setSiteId(freeMarker.getSiteId());
            column.setTempId(freeMarker.getTempletId());
            // 模板可视化时根据模板id获取任一条应用该模板的分类
            ResultDataStruct<Column> resultDataStruct = columnServiceClient.getColumnByTempletId(column);
            if (resultDataStruct.getCode() != 200) {
                throw new CustomMessageException(resultDataStruct.getCode(), resultDataStruct.getMessage());
            }
            column = resultDataStruct.getData();
            freeMarker.setColumnId(column.getColumnId());
            JSONObject jsonObject = getAnalyzePathByColumn(freeMarker, column);
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }


    /**
     * @author Mr.zheng
     * @Description getAnalyzePath 异步解析分类页静态地址
     * @Date 14:14 2018/8/23
     **/
    @Async
    protected JSONObject getAnalyzePathByColumn(FreeMarker freeMarker, Column column) throws Exception {
        PageTo pageTo = new PageTo();
        pageTo = getPageTo(column, pageTo);
        //将分类名称转为首字母拼写别名
        String columnNamme = HanyuPinyinHelper.getFirstLettersLo(column.getColumnName());
        JSONObject jsonObject = null;
        int i = 1;
        do {
            //当页数大于自定义页数时不再生成静态页
            if (i > column.getPageNum()) {
                break;
            }
            freeMarker.setTempletId(column.getTempId());
            freeMarker.setWapTempletId(column.getmFirstListTempletId());
            freeMarker.setWapOtherPageTempletId(column.getmListTempletId());
            freeMarker.setAliasName(columnNamme);
            freeMarker.setTime(column.getCreateTime());
            freeMarker.setColumnId(column.getColumnId());
            freeMarker.setChannelId("-1");
            //分页当前页数
            freeMarker.setPageNum(i);
            //3标识分类页面
            freeMarker.setStatus(COLUMNLIST);
            jsonObject = getJsonObject(freeMarker, column, i);
            i++;
        } while (i < pageTo.getPages() && freeMarker.getNote() == null);
        return jsonObject;
    }

    protected JSONObject getJsonObject(FreeMarker freeMarker, Column column, int i) throws Exception {
        ResultDataStruct resultDataStruct = analyzeColumnServiceClient.analyzeColumn(freeMarker);
        if(resultDataStruct.getCode() != 200){
            throw new CustomMessageException(resultDataStruct.getCode(),column.getColumnName() + "模板解析失败！错误信息：" + resultDataStruct.getMessage());
        }
        JSONObject jsonObject = (JSONObject) resultDataStruct.getData();
        if (i == 1 && freeMarker.getNote() == null) {
            //Mr.zheng:将每次生成该分类的静态资源则更新到数据库
            modifyColumnPath(column, jsonObject);
            log.info("更新路径:{}", column.getColumnName() + column.getManuscriptPath());
        }
        return (JSONObject) resultDataStruct.getData();
    }


    private void modifyColumnPath(Column column, JSONObject jsonObject) throws Exception {
        try {
            if (jsonObject != null) {
                column.setManuscriptPath("/" + jsonObject.getString("filePath"));
                columnServiceClient.modifyTemptId(column);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前分类下的文章列表的分页数据
     **/
    private PageTo getPageTo(Column column, PageTo pageParam) throws Exception {
        try {
            pageParam.setPageNum(1);
            pageParam.setPageSize(column.getPageSize() == null ? 5 : column.getPageSize());

            Article article = new Article();
            article.setColumnId(column.getColumnId());
            article.setSiteId(column.getSiteId());
            article.setAuditType(0);
            article.setDelTag(0);

            ParameterDataStruct<Article> parameterDataStruct = new ParameterDataStruct<>();
            parameterDataStruct.setData(article);
            parameterDataStruct.setPageTo(pageParam);
            //获取文章列表及其分页数据
            ResultPageStruct<Article> resultPageStruct = articleServiceClient.getArticleList(parameterDataStruct);

            return resultPageStruct.getPageInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new PageTo();
    }
}
